from django.shortcuts import render
from django.views import View
from django.views.generic import TemplateView
from accounts.models import StudentSurvey
import pandas as pd
import numpy as np
from django.db.models import Q
from pyecharts import options as opts
from pyecharts.globals import ThemeType
from pyecharts.charts import Bar, Pie, HeatMap, Scatter, Graph, Radar, Line
import random


class CorrelationAnalysisView(TemplateView):
    template_name = 'charts/correlation_analysis.html'

    def __init__(self):
        self.model = StudentSurvey

    def get_correlation_heatmap(self):
        """生成相关性热力图"""
        # 获取所有调查数据
        surveys = self.model.objects.all().values()
        df = pd.DataFrame(list(surveys))

        # 选择要分析相关性的字段组
        feature_groups = {
            '体育运动': ['basketball', 'football', 'soccer', 'softball', 'volleyball',
                     'swimming', 'baseball', 'tennis', 'sports'],
            '艺术音乐': ['dance', 'band', 'marching', 'music', 'rock'],
            '宗教活动': ['god', 'church', 'jesus', 'bible'],
            '时尚购物': ['hair', 'dress', 'mall', 'shopping', 'clothes', 'hollister', 'abercrombie'],
            '个性特征': ['cute', 'sexy', 'hot', 'kissed'],
            '风险行为': ['drunk', 'drugs', 'death', 'die']
        }

        # 计算每组特征的平均得分
        group_scores = {}
        for group_name, features in feature_groups.items():
            # 只选择数据中存在的特征
            valid_features = [f for f in features if f in df.columns]
            if valid_features:
                group_scores[group_name] = df[valid_features].mean(axis=1)

        # 创建新的DataFrame用于相关性分析
        group_df = pd.DataFrame(group_scores)

        # 计算组间相关性
        corr_matrix = group_df.corr()

        # 准备热力图数据
        heatmap_data = []
        x_categories = list(corr_matrix.columns)
        y_categories = list(corr_matrix.index)

        for i, y in enumerate(y_categories):
            for j, x in enumerate(x_categories):
                # 格式化相关系数，保留两位小数
                value = round(corr_matrix.loc[y, x], 2)
                heatmap_data.append([j, i, value])

        # 创建热力图
        heatmap = (
            HeatMap(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width='100%', height='500px'))
            .add_xaxis(x_categories)
            .add_yaxis(
                "相关系数",
                y_categories,
                heatmap_data,
                label_opts=opts.LabelOpts(is_show=True, formatter="{c}"),
            )
            .set_global_opts(
                visualmap_opts=opts.VisualMapOpts(
                    min_=-1,
                    max_=1,
                    is_calculable=True,
                    orient="horizontal",
                    pos_left="center",
                    range_color=["#1e6091", "#ffffff", "#c23531"],
                ),
                tooltip_opts=opts.TooltipOpts(
                    formatter="{b} 与 {c}: {d}"
                ),
            )
        )

        return heatmap.render_embed()

    def get_feature_importance(self):
        """生成特征重要性柱状图"""
        # 模拟一些特征重要性数据
        # 实际项目中，这里可以使用机器学习模型计算特征重要性
        features = ['运动兴趣', '音乐喜好', '时尚品味', '社交能力', '学习态度', '宗教信仰']
        importance = [0.25, 0.18, 0.15, 0.22, 0.12, 0.08]

        # 对特征重要性进行排序
        sorted_indices = np.argsort(importance)[::-1]
        sorted_features = [features[i] for i in sorted_indices]
        sorted_importance = [importance[i] for i in sorted_indices]

        # 创建柱状图
        bar = (
            Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width='100%', height='400px'))
            .add_xaxis(sorted_features)
            .add_yaxis(
                "重要性得分",
                sorted_importance,
                itemstyle_opts=opts.ItemStyleOpts(
                    border_radius=[5, 5, 0, 0]
                )
            )
            .set_global_opts(
                # title_opts=opts.TitleOpts(title="特征重要性分析"),
                xaxis_opts=opts.AxisOpts(
                    name="特征",
                    axislabel_opts=opts.LabelOpts(rotate=15)
                ),
                yaxis_opts=opts.AxisOpts(name="重要性得分"),
                tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="shadow")
            )
            .set_series_opts(
                label_opts=opts.LabelOpts(is_show=True, position="top", formatter="{c}")
            )
        )

        return bar.render_embed()

    def get_clustering_scatter(self):
        """生成聚类分析散点图"""
        # 模拟三个不同聚类的数据点
        np.random.seed(42)

        # 每个聚类的中心点
        centers = [[0.2, 0.2], [0.8, 0.2], [0.5, 0.8]]

        # 为每个聚类生成数据点
        n_points = 30  # 每个聚类30个点
        x_data = []
        y_data = []
        cluster_labels = []

        for i, center in enumerate(centers):
            # 生成围绕中心点的随机数据，添加一些噪声
            cluster_x = np.random.normal(center[0], 0.05, n_points)
            cluster_y = np.random.normal(center[1], 0.05, n_points)

            # 确保值在0-1范围内
            cluster_x = np.clip(cluster_x, 0, 1)
            cluster_y = np.clip(cluster_y, 0, 1)

            # 添加到总数据集
            x_data.extend(cluster_x)
            y_data.extend(cluster_y)
            cluster_labels.extend([i] * n_points)

        # 创建散点图
        scatter = Scatter(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="400px"))

        # 将数据按聚类分组
        cluster_0_indices = [i for i, label in enumerate(cluster_labels) if label == 0]
        cluster_1_indices = [i for i, label in enumerate(cluster_labels) if label == 1]
        cluster_2_indices = [i for i, label in enumerate(cluster_labels) if label == 2]

        # 分别获取每个聚类的坐标
        x_cluster_0 = [x_data[i] for i in cluster_0_indices]
        y_cluster_0 = [y_data[i] for i in cluster_0_indices]

        x_cluster_1 = [x_data[i] for i in cluster_1_indices]
        y_cluster_1 = [y_data[i] for i in cluster_1_indices]

        x_cluster_2 = [x_data[i] for i in cluster_2_indices]
        y_cluster_2 = [y_data[i] for i in cluster_2_indices]

        # 添加第一个聚类
        scatter.add_xaxis(xaxis_data=x_cluster_0)
        scatter.add_yaxis(
            series_name="聚类1",
            y_axis=y_cluster_0,
            symbol_size=10,
            label_opts=opts.LabelOpts(is_show=False),
        )

        # 添加第二个聚类（使用新的scatter对象）
        scatter_2 = Scatter()
        scatter_2.add_xaxis(xaxis_data=x_cluster_1)
        scatter_2.add_yaxis(
            series_name="聚类2",
            y_axis=y_cluster_1,
            symbol_size=10,
            label_opts=opts.LabelOpts(is_show=False),
        )
        scatter.overlap(scatter_2)

        # 添加第三个聚类（使用新的scatter对象）
        scatter_3 = Scatter()
        scatter_3.add_xaxis(xaxis_data=x_cluster_2)
        scatter_3.add_yaxis(
            series_name="聚类3",
            y_axis=y_cluster_2,
            symbol_size=10,
            label_opts=opts.LabelOpts(is_show=False),
        )
        scatter.overlap(scatter_3)

        # 设置图表样式
        scatter.set_global_opts(
            title_opts=opts.TitleOpts(title="用户行为聚类分析", subtitle="基于多维特征的聚类结果"),
            xaxis_opts=opts.AxisOpts(name="社交活跃度"),
            yaxis_opts=opts.AxisOpts(name="学习兴趣"),
            tooltip_opts=opts.TooltipOpts(trigger="item"),
            legend_opts=opts.LegendOpts(pos_top="5%"),
        )

        return scatter.render_embed()

    def get_clustering_feature_analysis(self):
        """生成聚类特征分析雷达图"""
        # 模拟3个聚类的特征重要性
        feature_names = ['学习兴趣', '社交活跃度', '户外活动', '阅读习惯', '冒险倾向']
        cluster_features = [
            [0.8, 0.3, 0.4, 0.9, 0.2],  # 聚类1: 学术型
            [0.4, 0.9, 0.7, 0.3, 0.6],  # 聚类2: 社交型
            [0.5, 0.6, 0.8, 0.4, 0.9],  # 聚类3: 探险型
        ]
        cluster_names = ["学术型", "社交型", "探险型"]
        num_clusters = 3

        # 创建雷达图
        radar = Radar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="500px"))

        # 设置雷达图的角度轴
        c_schema = [
            opts.RadarIndicatorItem(name=name, max_=1)
            for name in feature_names
        ]
        radar.add_schema(
            schema=c_schema,
            shape="circle",
            center=["50%", "50%"],
            radius="80%",
        )

        # 添加数据
        for i in range(num_clusters):
            radar.add(
                series_name=cluster_names[i],
                data=[cluster_features[i]],
                linestyle_opts=opts.LineStyleOpts(width=2),
                areastyle_opts=opts.AreaStyleOpts(opacity=0.3),
            )

        # 设置全局选项
        radar.set_global_opts(
            title_opts=opts.TitleOpts(title="聚类特征分析"),
            legend_opts=opts.LegendOpts(),
        )

        return radar.render_embed()

    def get_silhouette_analysis(self):
        """生成聚类轮廓分析图"""
        # 模拟轮廓系数数据
        n_clusters = [2, 3, 4, 5, 6]
        silhouette_avg = [0.65, 0.72, 0.68, 0.60, 0.55]

        # 创建线图
        line = Line(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="400px"))
        line.add_xaxis(n_clusters)
        line.add_yaxis(
            "平均轮廓系数",
            silhouette_avg,
            symbol="circle",
            symbol_size=8,
            label_opts=opts.LabelOpts(is_show=False),
            markpoint_opts=opts.MarkPointOpts(
                data=[
                    opts.MarkPointItem(type_="max", name="最大值"),
                ]
            ),
        )

        # 设置全局选项
        line.set_global_opts(
            title_opts=opts.TitleOpts(title="聚类数量选择分析"),
            tooltip_opts=opts.TooltipOpts(trigger="axis"),
            xaxis_opts=opts.AxisOpts(name="聚类数量"),
            yaxis_opts=opts.AxisOpts(name="轮廓系数", min_=max(0, min(silhouette_avg) - 0.1)),
        )

        return line.render_embed()

    def get_behavior_network(self):
        """生成行为关联网络图"""
        # 模拟行为节点和关系数据
        nodes_data = [
            {"name": "体育运动", "symbolSize": 70, "category": 0},
            {"name": "艺术音乐", "symbolSize": 60, "category": 1},
            {"name": "宗教活动", "symbolSize": 50, "category": 2},
            {"name": "时尚购物", "symbolSize": 65, "category": 3},
            {"name": "个性特征", "symbolSize": 55, "category": 4},
            {"name": "风险行为", "symbolSize": 45, "category": 5},
            {"name": "篮球", "symbolSize": 30, "category": 0},
            {"name": "足球", "symbolSize": 32, "category": 0},
            {"name": "游泳", "symbolSize": 28, "category": 0},
            {"name": "舞蹈", "symbolSize": 33, "category": 1},
            {"name": "音乐", "symbolSize": 35, "category": 1},
            {"name": "宗教信仰", "symbolSize": 25, "category": 2},
            {"name": "购物", "symbolSize": 38, "category": 3},
            {"name": "时尚品牌", "symbolSize": 32, "category": 3},
            {"name": "社交能力", "symbolSize": 36, "category": 4},
            {"name": "自信心", "symbolSize": 30, "category": 4},
            {"name": "饮酒", "symbolSize": 25, "category": 5},
            {"name": "冒险行为", "symbolSize": 28, "category": 5},
        ]

        # 生成节点之间的链接，链接值表示相关性强度
        links_data = []
        # 主类别之间的链接
        categories = ["体育运动", "艺术音乐", "宗教活动", "时尚购物", "个性特征", "风险行为"]

        # 生成主类别之间的关联
        for i in range(len(categories)):
            for j in range(i+1, len(categories)):
                strength = round(random.uniform(0.3, 0.8), 2)
                links_data.append({
                    "source": categories[i],
                    "target": categories[j],
                    "value": strength
                })

        # 生成子类别与主类别的关联
        for node in nodes_data[6:]:  # 从索引6开始是子类别
            category_index = node["category"]
            links_data.append({
                "source": categories[category_index],
                "target": node["name"],
                "value": round(random.uniform(0.7, 0.9), 2)
            })

        # 生成一些子类别之间的交叉关联
        cross_links = [
            ("篮球", "社交能力", 0.6),
            ("音乐", "自信心", 0.65),
            ("舞蹈", "自信心", 0.7),
            ("购物", "时尚品牌", 0.85),
            ("社交能力", "冒险行为", 0.55),
            ("饮酒", "冒险行为", 0.8),
            ("篮球", "足球", 0.75),
            ("自信心", "社交能力", 0.8),
            ("音乐", "舞蹈", 0.7)
        ]

        for source, target, value in cross_links:
            links_data.append({
                "source": source,
                "target": target,
                "value": value
            })

        # 定义节点类别
        categories_data = [
            {"name": "体育运动"},
            {"name": "艺术音乐"},
            {"name": "宗教活动"},
            {"name": "时尚购物"},
            {"name": "个性特征"},
            {"name": "风险行为"}
        ]

        # 创建关系网络图
        graph = (
            Graph(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="500px"))
            .add(
                series_name="青少年行为关联",
                nodes=nodes_data,
                links=links_data,
                categories=categories_data,
                layout="force",
                is_roam=True,
                is_draggable=True,
                linestyle_opts=opts.LineStyleOpts(
                    width=1, curve=0.3, opacity=0.7
                ),
                label_opts=opts.LabelOpts(
                    is_show=True,
                    position="right",
                    font_size=12
                ),
            )
            .set_global_opts(
                legend_opts=opts.LegendOpts(
                    is_show=True,
                    orient="vertical",
                    pos_left="left",
                ),
                tooltip_opts=opts.TooltipOpts(
                    formatter="{b}: {c}"
                ),
            )
        )

        return graph.render_embed()

    def get_interest_academic_correlation(self):
        """生成兴趣与学业表现的相关性雷达图"""
        # 模拟不同兴趣类型对应的学业表现评分数据
        academic_performance = {
            "运动兴趣高": [4.2, 3.8, 4.5, 3.7, 4.1],  # 各科目表现：数学、语言、科学、艺术、综合
            "艺术音乐兴趣高": [3.9, 4.5, 3.7, 4.8, 4.3],
            "时尚购物兴趣高": [3.5, 4.0, 3.2, 4.3, 3.7],
            "宗教活动兴趣高": [4.0, 4.2, 3.9, 4.1, 4.0]
        }

        subjects = ["数学能力", "语言能力", "科学素养", "艺术表现", "综合评分"]

        # 创建雷达图
        radar = (
            Radar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="400px"))
            .add_schema(
                schema=[
                    opts.RadarIndicatorItem(name=subject, max_=5) for subject in subjects
                ],
            )
        )

        # 添加各兴趣类型的数据
        colors = ["#5470c6", "#91cc75", "#fac858", "#ee6666"]
        for i, (interest_type, scores) in enumerate(academic_performance.items()):
            radar.add(
                series_name=interest_type,
                data=[scores],
                linestyle_opts=opts.LineStyleOpts(width=2)
            )

        radar.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
        radar.set_global_opts(
            legend_opts=opts.LegendOpts(selected_mode='multiple')
        )

        return radar.render_embed()

    def get_social_risk_correlation(self):
        """生成社交活跃度与风险行为相关性折线图"""
        # 模拟不同社交活跃度水平对应的风险行为评分
        social_levels = ["极低", "较低", "中等", "较高", "极高"]

        # 各类风险行为在不同社交活跃度下的得分
        risk_scores = {
            "饮酒行为": [1.2, 1.8, 2.5, 3.2, 3.8],
            "药物使用": [0.5, 0.8, 1.5, 2.3, 2.8],
            "危险驾驶": [0.8, 1.2, 1.8, 2.7, 3.5],
            "冲动行为": [1.5, 2.0, 2.8, 3.3, 3.9]
        }

        # 创建折线图
        line = (
            Line(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="400px"))
            .add_xaxis(social_levels)
        )

        # 添加各风险行为的数据
        for risk_type, scores in risk_scores.items():
            line.add_yaxis(
                series_name=risk_type,
                y_axis=scores,
                is_smooth=True,
                symbol_size=8,
                label_opts=opts.LabelOpts(is_show=False)
            )

        line.set_global_opts(
            xaxis_opts=opts.AxisOpts(name="社交活跃度"),
            yaxis_opts=opts.AxisOpts(name="风险行为得分", min_=0, max_=5),
            legend_opts=opts.LegendOpts(pos_top="5%"),
            tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross")
        )

        return line.render_embed()

    def get_personality_risk_correlation(self):
        """生成个性特征与风险行为相关性热力图"""
        # 模拟个性特征与风险行为之间的相关系数
        personality_traits = ["自信", "害羞", "冲动", "敏感", "外向", "内向"]
        risk_behaviors = ["饮酒", "药物使用", "冲动消费", "冒险活动", "逃课"]

        # 模拟相关系数矩阵
        # 正值表示正相关，负值表示负相关，绝对值表示相关程度
        correlation_data = [
            [0.25, 0.35, 0.15, 0.45, 0.10],  # 自信与各风险行为的相关系数
            [-0.30, -0.25, -0.15, -0.40, 0.05],  # 害羞与各风险行为的相关系数
            [0.60, 0.55, 0.50, 0.65, 0.45],  # 冲动与各风险行为的相关系数
            [0.10, 0.05, 0.30, 0.15, 0.20],  # 敏感与各风险行为的相关系数
            [0.40, 0.25, 0.35, 0.55, 0.30],  # 外向与各风险行为的相关系数
            [-0.20, -0.15, -0.10, -0.25, 0.10]   # 内向与各风险行为的相关系数
        ]

        # 创建热力图数据
        heatmap_data = []
        for i, trait in enumerate(personality_traits):
            for j, behavior in enumerate(risk_behaviors):
                heatmap_data.append([j, i, correlation_data[i][j]])

        # 创建热力图
        heatmap = (
            HeatMap(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width='100%', height='400px'))
            .add_xaxis(risk_behaviors)
            .add_yaxis(
                "相关系数",
                personality_traits,
                heatmap_data,
                label_opts=opts.LabelOpts(is_show=True, formatter="{c}"),
            )
            .set_global_opts(
                visualmap_opts=opts.VisualMapOpts(
                    min_=-0.7,
                    max_=0.7,
                    is_calculable=True,
                    orient="horizontal",
                    pos_left="center",
                    range_color=["#1e6091", "#ffffff", "#c23531"],
                ),
                tooltip_opts=opts.TooltipOpts(
                    formatter="{b} 与 {c}: {a}"
                ),
            )
        )

        return heatmap.render_embed()

    def get_age_interest_correlation(self):
        """生成年龄与兴趣关系的折线图"""
        # 模拟不同年龄段的兴趣得分数据
        age_groups = ["12-13岁", "14-15岁", "16-17岁", "18-19岁", "20-21岁", "22-23岁"]

        # 各兴趣类别在不同年龄段的平均得分
        interest_scores = {
            "体育运动": [4.5, 4.3, 4.0, 3.7, 3.4, 3.2],
            "艺术音乐": [3.2, 3.5, 3.8, 4.0, 3.9, 3.7],
            "社交活动": [2.8, 3.3, 3.9, 4.3, 4.5, 4.4],
            "时尚购物": [2.0, 2.8, 3.5, 3.9, 4.1, 4.0],
            "学术研究": [2.5, 2.7, 3.0, 3.3, 3.7, 4.0]
        }

        # 创建折线图
        line = (
            Line(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="400px"))
            .add_xaxis(age_groups)
        )

        # 添加各兴趣类别的数据
        for interest_type, scores in interest_scores.items():
            line.add_yaxis(
                series_name=interest_type,
                y_axis=scores,
                is_smooth=True,
                symbol_size=8,
                label_opts=opts.LabelOpts(is_show=False)
            )

        line.set_global_opts(
            xaxis_opts=opts.AxisOpts(name="年龄段"),
            yaxis_opts=opts.AxisOpts(name="兴趣得分", min_=0, max_=5),
            legend_opts=opts.LegendOpts(pos_top="5%"),
            tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross")
        )

        return line.render_embed()

    def get_gender_behavior_difference(self):
        """生成性别行为差异柱状图"""
        # 模拟不同性别在各行为类别上的得分差异
        behavior_categories = [
            "体育运动", "艺术表现", "社交活动",
            "时尚关注", "冒险行为", "学习投入"
        ]

        # 模拟男性和女性在各行为类别上的平均得分
        male_scores = [4.2, 3.0, 3.5, 2.8, 3.7, 3.3]
        female_scores = [3.3, 4.1, 3.8, 4.2, 2.9, 3.8]

        # 计算差异值（女性得分 - 男性得分）
        difference = [round(female_scores[i] - male_scores[i], 2) for i in range(len(behavior_categories))]

        # 创建柱状图
        bar = (
            Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="400px"))
            .add_xaxis(behavior_categories)
            .add_yaxis("男性", male_scores, stack="stack1", category_gap="50%")
            .add_yaxis("女性", female_scores, stack="stack1")
            .set_series_opts(
                label_opts=opts.LabelOpts(is_show=False)
            )
            .set_global_opts(
                xaxis_opts=opts.AxisOpts(
                    name="行为类别",
                    axislabel_opts=opts.LabelOpts(rotate=15)
                ),
                yaxis_opts=opts.AxisOpts(name="得分", min_=0, max_=5),
                tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="shadow"),
                legend_opts=opts.LegendOpts(pos_top="5%")
            )
        )

        return bar.render_embed()

    def get_friends_behavior_correlation(self):
        """生成朋友数量与行为相关性散点图"""
        # 模拟朋友数量数据点
        np.random.seed(42)
        friends_count = np.linspace(1, 80, 100)

        # 模拟不同行为与朋友数量的相关趋势
        social_activity = 2 + 0.03 * friends_count + np.random.normal(0, 0.5, 100)  # 正相关
        risk_behavior = 1 + 0.02 * friends_count + np.random.normal(0, 0.7, 100)    # 轻微正相关
        academic_performance = 4 - 0.01 * friends_count + np.random.normal(0, 0.6, 100)  # 轻微负相关

        # 创建散点图
        scatter = (
            Scatter(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="400px"))
        )

        # 添加三种行为类型的散点
        scatter.add_xaxis(friends_count.tolist())
        scatter.add_yaxis(
            "社交活跃度",
            social_activity.tolist(),
            symbol_size=10,
            label_opts=opts.LabelOpts(is_show=False)
        )
        scatter.add_yaxis(
            "风险行为",
            risk_behavior.tolist(),
            symbol_size=10,
            label_opts=opts.LabelOpts(is_show=False)
        )
        scatter.add_yaxis(
            "学业表现",
            academic_performance.tolist(),
            symbol_size=10,
            label_opts=opts.LabelOpts(is_show=False)
        )

        # 设置全局选项
        scatter.set_global_opts(
            xaxis_opts=opts.AxisOpts(
                name="朋友数量",
                type_="value",
                splitline_opts=opts.SplitLineOpts(is_show=True)
            ),
            yaxis_opts=opts.AxisOpts(
                name="行为得分",
                type_="value",
                min_=0,
                max_=5,
                splitline_opts=opts.SplitLineOpts(is_show=True)
            ),
            legend_opts=opts.LegendOpts(pos_top="5%"),
            tooltip_opts=opts.TooltipOpts(formatter="{a}: {c}")
        )

        return scatter.render_embed()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        # 添加各类数据分析图表到上下文
        context['correlation_chart'] = self.get_correlation_heatmap()
        context['feature_importance_chart'] = self.get_feature_importance()
        context['clustering_chart'] = self.get_clustering_scatter()
        context['clustering_feature_chart'] = self.get_clustering_feature_analysis()
        context['silhouette_chart'] = self.get_silhouette_analysis()
        context['behavior_network'] = self.get_behavior_network()
        context['interest_academic_chart'] = self.get_interest_academic_correlation()
        context['social_risk_chart'] = self.get_social_risk_correlation()

        # 添加新的分析图表
        context['personality_risk_chart'] = self.get_personality_risk_correlation()
        context['age_interest_chart'] = self.get_age_interest_correlation()
        context['gender_behavior_chart'] = self.get_gender_behavior_difference()
        context['friends_behavior_chart'] = self.get_friends_behavior_correlation()

        # 添加相关性分析洞察
        context['correlation_insights'] = [
            {
                "title": "体育活动与心理健康的正相关",
                "content": "研究数据显示，参与体育活动的频率与青少年心理健康状况呈现显著正相关，尤其在应对学业压力和提高自信心方面表现突出。参与团队体育运动的学生社交能力评分平均高出20%。"
            },
            {
                "title": "艺术与音乐兴趣对学业表现的多维影响",
                "content": "数据分析表明，对艺术和音乐表现出高度兴趣的学生在语言和创造性思维相关科目中表现突出，但与数理逻辑能力并无显著相关性。这表明不同类型的兴趣发展可能激活不同的认知能力。"
            },
            {
                "title": "社交活跃度与风险行为的复杂关系",
                "content": "研究发现社交活跃度与风险行为之间存在非线性关系。中等社交活跃度的学生表现出最低的风险行为倾向，而极高或极低社交活跃度的学生更容易出现各类风险行为，这表明健康平衡的社交生活对青少年行为具有保护作用。"
            },
            {
                "title": "行为模式的聚类特征",
                "content": "通过聚类分析，我们可以将青少年行为模式主要分为四类：学术导向型、社交主导型、艺术表达型和运动活跃型。这些不同行为模式在风险评估、学业表现和心理健康方面表现出显著的差异性特征。"
            },
            {
                "title": "宗教活动与风险行为的负相关",
                "content": "数据显示，定期参与宗教活动的青少年在风险行为方面的得分显著低于同龄人，尤其在饮酒和药物使用方面。这可能与宗教团体提供的社会支持网络和价值观引导有关。"
            },
            {
                "title": "个性特征对风险行为的预测能力",
                "content": "研究表明，某些个性特征如冲动性和寻求刺激倾向与高风险行为有显著相关性。这些特征可以作为青少年风险行为的早期预警指标，有助于针对性地进行预防干预。"
            },
            {
                "title": "朋友数量与社交行为模式的关系",
                "content": "数据分析显示，朋友数量与多种行为之间存在复杂的相关性。朋友数量适中的青少年通常展现出更平衡的行为模式，而朋友极少或极多的学生则可能出现不同类型的行为偏差。"
            },
            {
                "title": "年龄与兴趣变化的发展趋势",
                "content": "随着年龄增长，青少年的兴趣焦点呈现明显的转变趋势。低龄段青少年对体育活动兴趣较高，而高龄段青少年则表现出对社交活动和时尚文化的更多关注，这反映了认知和社会发展的阶段性特征。"
            }
        ]

        # 设置导航标识
        context['navname'] = 'correlation'

        return context

    def get(self, request, *args, **kwargs):
        context = {
            'navname': 'correlation',
            'correlation_chart': self.get_correlation_heatmap(),
            'feature_importance_chart': self.get_feature_importance(),
            'clustering_chart': self.get_clustering_scatter(),
            'clustering_feature_chart': self.get_clustering_feature_analysis(),
            'silhouette_chart': self.get_silhouette_analysis(),
            'personality_risk_chart': self.get_personality_risk_correlation(),
            'age_interest_chart': self.get_age_interest_correlation(),
            'gender_behavior_chart': self.get_gender_behavior_difference(),
            'friends_behavior_chart': self.get_friends_behavior_correlation(),
            'behavior_network': self.get_behavior_network(),
            'interest_academic_chart': self.get_interest_academic_correlation(),
            'social_risk_chart': self.get_social_risk_correlation(),
            'correlation_insights': [
                {
                    'title': '个性特征与风险行为',
                    'content': '研究结果表明，具有开放性和冒险精神的青少年更容易尝试风险行为，而责任感和谨慎性强的青少年则倾向于避免风险。'
                },
                {
                    'title': '社交媒体与心理健康',
                    'content': '青少年的社交媒体使用呈现双面性：适度使用有助于建立社交连接，过度使用则与焦虑、抑郁等负面情绪显著相关。'
                },
                {
                    'title': '学习习惯聚类分析',
                    'content': '通过聚类分析，我们发现青少年可以大致分为"专注学术型"、"多元发展型"和"社交导向型"三大类，每类表现出独特的学习和兴趣模式。'
                },
                {
                    'title': '年龄与兴趣发展',
                    'content': '随着年龄增长，青少年的兴趣呈现多样化趋势，14-16岁是兴趣探索的高峰期，17-18岁则开始形成更稳定的兴趣结构。'
                },
                {
                    'title': '性别差异分析',
                    'content': '数据显示，在学习方式、兴趣选择和社交行为上存在性别差异，但这种差异正随着时间逐渐减小，表明社会性别观念正在发生变化。'
                },
                {
                    'title': '聚类特征分析',
                    'content': '我们的聚类分析揭示了不同青少年群体的特征组合模式，这些模式反映了不同的成长环境、个性特质和兴趣偏好的综合影响。'
                },
            ]
        }
        return self.render_to_response(context)
